<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use Hyperf\DbConnection\Db;
use App\Model\Goods;
use App\Model\User;

class GoodsService extends BaseService
{

    public function list(array $params)
    {
        $model = Goods::query()->select('id','category','title','image','price','num')->where('category_id', $params['category_id']);
        $list = $this->usePage($model)->toArray();

        return $list;
    }

    public function detail(array $params)
    {
        $user = auth();
        $goods = Goods::query()->select('id','goods_no','category','title','image','price','num','content')->where('id', $params['id'])->first();
        if(!$goods)
        {
            throw new ApiException(ErrorCode::WARNING, '商品不存在');
        }

        $goods['star_currency'] = $user['star_currency'];           //星币余额

        return $goods;
    }

    public function goods_exchange(array $params)
    {
        $user = auth();
        $user = User::query()->select('star_currency')->where('id', $user['id'])->first();      //获取用户实时星币余额
        $goods = Goods::query()->select('id','goods_no','category','title','image','price','num','content')->where('id', $params['id'])->first();
        if(!$goods)
        {
            throw new ApiException(ErrorCode::WARNING, '商品不存在');
        }

        if($params['num'] > $goods['num'])
        {
            throw new ApiException(ErrorCode::WARNING, '库存不足');
        }
        if($user['star_currency'] < ($goods['price']*$params['num']))
        {
            throw new ApiException(ErrorCode::WARNING, '星币不足');
        }

        $userData['star_currency'] = $user['star_currency'] - ($goods['price']*$params['num']);
        $orderdata['user_id'] = $user['id'];
        $orderdata['order_no'] = get_order_no();
        $orderdata['status'] = 1;        //待发货
        $orderdata['price'] = $goods['price']*$params['num'];
        Db::beginTransaction();
        try{
            User::query()->where('id', $user['id'])->update($userData);
            Order::query()->insert($orderdata);

            Db::commit();
        } catch(\Throwable $e){
            Db::rollBack();
            throw new ApiException(ErrorCode::ERROR, $e->getMessage());
        }

        return [];
    }

}